import React, { Component } from 'react';
import webviews from '../webviews.js';
import PasswordManagers from './passwordManager.js';
import MyHidden from '../../MyHidden'
import * as store from '../../reducers/partsSlice';
import SaveIcon from '@mui/icons-material/Save';
import RemoveRedEyeIcon from '@mui/icons-material/RemoveRedEye';
import IconButton from '@mui/material/IconButton';
export default class PasswordCapture extends Component {
  constructor() {
    super();
    this.state = {
      currentDomain: '',
      description_textContent: '',
      passwordInput_type: 'password',
      revealButton_classList: 'i carbon:view',
      username: '',
      password: '',
    };
    this.ref_usernameInput = React.createRef();
    this.ref_passwordInput = React.createRef();
    PasswordCapture.instance = this;
  }
  componentDidMount() {
    console.log('PasswordCapture componentDidMount==');
  }
  hideCaptureBar = () => {
    this.props.dispatch(store.actions.SHOW_CAPTURE(false));
  };
  togglePasswordVisibility = () => {
    if (this.state.passwordInput_type === 'password') {
      this.setState({
        passwordInput_type: 'text',
        revealButton_classList: 'i carbon:view-off',
      });
    } else {
      this.setState({
        passwordInput_type: 'password',
        revealButton_classList: 'i carbon:view',
      });
    }
  };
  static showCaptureBar = (username, password) => {
    PasswordCapture.instance.showCaptureBar(username, password);
  };
  showCaptureBar = (username, password) => {
    this.props.dispatch(store.actions.SHOW_CAPTURE(true));
    var description_textContent = l('passwordCaptureSavePassword').replace(
      '%s',
      this.state.currentDomain
    );
    this.setState(
      {
        description_textContent: description_textContent,
        passwordInput_type: 'password',
        revealButton_classList: 'i carbon:view-off',
        username: username || '',
        password: password || '',
      }
    );
  };
  save_click = () => {
    if (
      this.ref_usernameInput.current.checkValidity() &&
      this.ref_passwordInput.current.checkValidity()
    ) {
      PasswordManagers.getConfiguredPasswordManager().then((manager) => {
        manager.saveCredential(
          this.state.currentDomain,
          this.state.username,
          this.state.password
        );
        this.hideCaptureBar();
      });
    }
  };
  static handleRecieveCredentials = (tab, args, frameId) => {
    PasswordCapture.instance.handleRecieveCredentials(tab, args, frameId);
  };
  handleRecieveCredentials = (tab, args, frameId) => {
    var domain = args[0][0];
    if (domain.startsWith('www.')) {
      domain = domain.slice(4);
    }

    var username = args[0][1][0] || '';
    var password = args[0][2][0] || '';
    PasswordManagers.getConfiguredPasswordManager().then((manager) => {
      if (!manager || !manager.saveCredential) {
        // the password can't be saved
        return;
      }

      // check if this username/password combo is already saved
      manager.getSuggestions(domain).then((credentials) => {
        var alreadyExists = credentials.some(
          (cred) => cred.username === username && cred.password === password
        );
        if (!alreadyExists) {
          // this.hideCaptureBar();
          this.setState({ currentDomain: domain });
          this.showCaptureBar(username, password);
        }
      });
    });
  };

  username_change = (event) => {
    this.setState({ username: event.target.value });
  };
  password_change = (event) => {
    this.setState({ password: event.target.value });
  };
  render() {
    return (
      <MyHidden title="" on_hidden={() => {
        this.props.dispatch(store.partsSlice.actions.SHOW_CAPTURE(false))
      }} hidden={!this.props.state.show_capture}>
        <div
          id="password-capture-bar"
          style={{ display: "flex" }}
        >
          <span id="password-capture-description">
            {this.state.description_textContent}
          </span>
          <input
            id="password-capture-username"
            ref={this.ref_usernameInput}
            placeholder={'username'}
            onChange={this.username_change}
            value={this.state.username}
            type="text"
            required
          />
          <span className="password-capture-section">
            <input
              id="password-capture-password"
              ref={this.ref_passwordInput}
              placeholder={'password'}
              onChange={this.password_change}
              type={this.state.passwordInput_type}
              value={this.state.password}
              required
            />
            <IconButton
              onClick={this.togglePasswordVisibility}
              id="password-capture-reveal-password"
              className={this.state.revealButton_classList}
            ><RemoveRedEyeIcon /></IconButton>
          </span>
          <span className="password-capture-section">
            <IconButton
              id="password-capture-save"
              onClick={this.save_click}
              data-string="passwordCaptureSave"
            ><SaveIcon /></IconButton>
          </span>
        </div>
      </MyHidden>
    );
  }
}
